package com.sbwebsocket.core.redis;

import cn.hutool.core.collection.CollUtil;
import com.sbwebsocket.core.redis.model.contants.WsMessageRedisKeyPrefix;
import com.sbwebsocket.core.service.TopicMessageManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Auther: GSJ
 * @Date: 2022/3/4
 * @Description:
 * @version: 1.0
 */
public class RedisTopicMessageManager implements TopicMessageManager {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public boolean subscribe(List<String> clientkeys, String topic) {
        if (CollUtil.isEmpty(clientkeys)) return false;
        Long size = redisTemplate.opsForSet().add(WsMessageRedisKeyPrefix.SERVER_MSG_TOPIC + topic,
                clientkeys.toArray(new String[clientkeys.size()]));
        return size > 0;
    }

    @Override
    public boolean subscribe(String clientkey, String topic) {
        Long size = redisTemplate.opsForSet().add(WsMessageRedisKeyPrefix.SERVER_MSG_TOPIC + topic,
                clientkey);
        return size > 0;
    }

    @Override
    public boolean unsubscribe(String clientkey, String topic) {
        Long remove = redisTemplate.opsForSet().remove(WsMessageRedisKeyPrefix.SERVER_MSG_TOPIC + topic, clientkey);
        return remove > 0;
    }

    @Override
    public boolean unsubscribe(List<String> clientkeys, String topic) {
        Long remove = redisTemplate.opsForSet().remove(WsMessageRedisKeyPrefix.SERVER_MSG_TOPIC + topic, clientkeys.toArray(new String[clientkeys.size()]));
        return remove > 0;
    }
}
